package com.example.timmy.myapplication.ui.activity;

import android.os.Bundle;
import android.os.Environment;
import android.support.v7.app.AppCompatActivity;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

import com.example.timmy.myapplication.R;
import com.example.timmy.myapplication.utils.Constans;
import com.iflytek.cloud.ErrorCode;
import com.iflytek.cloud.InitListener;
import com.iflytek.cloud.SpeechConstant;
import com.iflytek.cloud.SpeechError;
import com.iflytek.cloud.SpeechSynthesizer;
import com.iflytek.cloud.SynthesizerListener;
import com.iflytek.sunflower.FlowerCollector;

import java.util.UUID;

import static com.example.timmy.myapplication.R.id.synthesis;

public class SpeechActivity extends AppCompatActivity implements View.OnClickListener {

    private static final String TAG = MainActivity.class.getSimpleName();
    private Button mButton;
    private SpeechSynthesizer mTts;

    // 默认发声人
    private String voicer = "xiaoqi";

    // 引擎类型
    private String mEngineType = SpeechConstant.TYPE_CLOUD;
    private EditText mEditText;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_speech);
        initSpeech();
        initView();
    }

    // 初始化科大讯飞
    private void initSpeech() {
        mTts = SpeechSynthesizer.createSynthesizer(SpeechActivity.this, mTtsInitListener);
    }

    private void initView() {

        mEditText = (EditText) findViewById(R.id.edit_text);

        mButton = (Button) findViewById(synthesis);
        findViewById(R.id.btn_fwc).setOnClickListener(this);
        findViewById(R.id.btn_pbzc).setOnClickListener(this);
        findViewById(R.id.btn_jf).setOnClickListener(this);
        findViewById(R.id.btn_sdt).setOnClickListener(this);
        findViewById(R.id.btn_sd).setOnClickListener(this);
        findViewById(R.id.btn_ywqz).setOnClickListener(this);

        mButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                String s = mEditText.getText().toString();

                if (!TextUtils.isEmpty(s)) {
                    synthesis(s);
                } else {
                    Toast.makeText(SpeechActivity.this, "未输入", Toast.LENGTH_SHORT).show();
                }
            }
        });
    }

    // 点击了合成按钮
    private void synthesis(String text) {
        Toast.makeText(this, "点击了", Toast.LENGTH_SHORT).show();

        FlowerCollector.onEvent(SpeechActivity.this, "tts_play");

        // 设置参数
        setParam(text);

        int code = mTts.startSpeaking(text, mTtsListener);

        if (code != ErrorCode.SUCCESS) {
            Log.i(TAG, "语音合成成功....");
        }
    }

    private void setParam(String text) {
        // 清空参数
        mTts.setParameter(SpeechConstant.PARAMS, null);

        // 根据合成引擎设置相应参数
        if (mEngineType.equals(SpeechConstant.TYPE_CLOUD)) {
            mTts.setParameter(SpeechConstant.ENGINE_TYPE, SpeechConstant.TYPE_CLOUD);
            // 设置在线合成发音人
            mTts.setParameter(SpeechConstant.VOICE_NAME, voicer);
            //设置合成语速
            mTts.setParameter(SpeechConstant.SPEED, "50");
            //设置合成音调
            mTts.setParameter(SpeechConstant.PITCH, "50");
            //设置合成音量
            mTts.setParameter(SpeechConstant.VOLUME, "90");
        } else {
            mTts.setParameter(SpeechConstant.ENGINE_TYPE, SpeechConstant.TYPE_LOCAL);
            // 设置本地合成发音人 voicer为空，默认通过语记界面指定发音人。
            mTts.setParameter(SpeechConstant.VOICE_NAME, "");
            /**
             * TODO 本地合成不设置语速、音调、音量，默认使用语记设置
             * 开发者如需自定义参数，请参考在线合成参数设置
             */
        }
        //设置播放器音频流类型
        mTts.setParameter(SpeechConstant.STREAM_TYPE, "3");
        // 设置播放合成音频打断音乐播放，默认为true
        mTts.setParameter(SpeechConstant.KEY_REQUEST_FOCUS, "true");

        // 设置音频保存路径，保存音频格式支持pcm、wav，设置路径为sd卡请注意WRITE_EXTERNAL_STORAGE权限
        // 注：AUDIO_FORMAT参数语记需要更新版本才能生效
        mTts.setParameter(SpeechConstant.AUDIO_FORMAT, "wav");

        String uuid = UUID.randomUUID().toString();
        mTts.setParameter(SpeechConstant.TTS_AUDIO_PATH, Environment.getExternalStorageDirectory() + "/msc/" + text + ".wav");
    }

    // ==========================================
    /**
     * 初始化监听。
     */
    private InitListener mTtsInitListener = new InitListener() {
        @Override
        public void onInit(int code) {
            Log.d(TAG, "InitListener init() code = " + code);
            if (code != ErrorCode.SUCCESS) {
                // showTip("初始化失败,错误码：" + code);
            } else {
                // 初始化成功，之后可以调用startSpeaking方法
                // 注：有的开发者在onCreate方法中创建完合成对象之后马上就调用startSpeaking进行合成，
                // 正确的做法是将onCreate中的startSpeaking调用移至这里
            }
        }
    };

    private SynthesizerListener mTtsListener = new SynthesizerListener() {

        @Override
        public void onSpeakBegin() {
            Log.i(TAG, "开始播放");
        }

        @Override
        public void onBufferProgress(int i, int i1, int i2, String s) {
            Log.i(TAG, "合成进度: " + i);
        }

        @Override
        public void onSpeakPaused() {
            Log.i(TAG, "暂停播放");
        }

        @Override
        public void onSpeakResumed() {
            Log.i(TAG, "继续播放");
        }

        @Override
        public void onSpeakProgress(int i, int i1, int i2) {
            Log.i(TAG, "缓冲进度: " + i);
        }

        @Override
        public void onCompleted(SpeechError speechError) {
            if (speechError == null) {
                Log.i(TAG, "播放完成");
            } else if (speechError != null) {
                Toast.makeText(SpeechActivity.this, speechError.getPlainDescription(true), Toast.LENGTH_SHORT).show();
            }
        }

        @Override
        public void onEvent(int i, int i1, int i2, Bundle bundle) {
        }
    };

    @Override
    protected void onDestroy() {
        super.onDestroy();

        if (null != mTts) {
            mTts.stopSpeaking();
            // 退出时释放连接
            mTts.destroy();
        }
    }

    int fwcCount = 0;
    int pbzcCount = 0;
    int sdCount = 0;
    int sdtCount = 0;
    int ywqzCount = 0;
    int jfCount = 0;


    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.btn_fwc:

                String[] fwcErrorMessage = Constans.fwcErrorMessage;

                if (fwcCount != fwcErrorMessage.length) {
                    // synthesis(fwcErrorMessage[fwcCount]);
                    fwcCount++;
                } else {
                    Toast.makeText(this, "没有了", Toast.LENGTH_SHORT).show();
                }

                synthesis("完美");

                break;
            case R.id.btn_pbzc:

                String[] pbzcErrorMessage = Constans.pbzcErrorMessage;

                synthesis("漂亮");
                if (pbzcCount != pbzcErrorMessage.length) {
                    // synthesis(pbzcErrorMessage[pbzcCount]);
                    pbzcCount++;
                } else {
                    Toast.makeText(this, "没有了", Toast.LENGTH_SHORT).show();
                }
                break;
            case R.id.btn_sd:
                String[] sdErrorMessage = Constans.sdErrorMessage;

                if (sdCount != sdErrorMessage.length) {
                    synthesis(sdErrorMessage[sdCount]);
                    sdCount++;
                } else {
                    Toast.makeText(this, "没有了", Toast.LENGTH_SHORT).show();
                }
                break;
            case R.id.btn_sdt:

                String[] sdtErrorMessage = Constans.sdtErrorMessage;
                if (sdtCount != sdtErrorMessage.length) {
                    synthesis(sdtErrorMessage[sdtCount]);
                    sdtCount++;
                } else {
                    Toast.makeText(this, "没有了", Toast.LENGTH_SHORT).show();
                }
                break;
            case R.id.btn_ywqz:
                String[] ywqzErrorMessage = Constans.ywqzErrorMessage;
                if (ywqzCount != ywqzErrorMessage.length) {
                    synthesis(ywqzErrorMessage[ywqzCount]);
                    ywqzCount++;
                } else {
                    Toast.makeText(this, "没有了", Toast.LENGTH_SHORT).show();
                }
                break;
            case R.id.btn_jf:

                String[] jfErrorMessage = Constans.jfErrorMessage;
                if (jfCount != jfErrorMessage.length) {
                    synthesis(jfErrorMessage[jfCount]);
                    jfCount++;
                } else {
                    Toast.makeText(this, "没有了", Toast.LENGTH_SHORT).show();
                }
                break;
        }

    }
}
